﻿using System;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using DotNetApp.Toolkit.Requests;
using WinSource.Model;

namespace WinSource.Client
{
    internal class GetArticlesFromRssRequest : Request<GetArticlesRequestArgs>
    {
        #region Constants

        private const string Url = "http://winsource.com/feed/";

        #endregion

        #region Constructor

        public GetArticlesFromRssRequest(Action<GetArticlesRequestArgs> callback = null)
            : base(callback)
        {
        }

        #endregion

        #region Properties

        protected override string Link
        {
            get { return Url; }
        }

        #endregion

        #region Request Overrides

        protected override void OnRequestCompleted(RequestResponseEventArgs requestResponseEventArgs)
        {
            if (!requestResponseEventArgs.Cancelled)
            {
                GetArticlesRequestArgs getArticlesRequestArgs = new GetArticlesRequestArgs(requestResponseEventArgs.Error == null, ResponseTimeInMs);

                if (requestResponseEventArgs.Error == null)
                {
                    try
                    {
                        XDocument xDocument = XDocument.Parse(requestResponseEventArgs.Result);
                        XElement rssElement = xDocument.Element("rss");
                        
                        if (rssElement != null)
                        {
                            XElement channelElement = rssElement.Element("channel");

                            if (channelElement != null)
                            {
                                foreach (XElement itemElement in channelElement.Descendants("item"))
                                {
                                    string guid = GetElementValue(itemElement, "guid").Replace("http://winsource.com/?p=", "");
                                    string publishDateText = GetElementValue(itemElement, "pubDate");

                                    DateTime publishDate;
                                    DateTime.TryParse(publishDateText, out publishDate);

                                    XNamespace content = XNamespace.Get("http://purl.org/rss/1.0/modules/content/");
                                    XElement elementEncoded = itemElement.Element(content + "encoded");
                                    
                                    if (elementEncoded != null)
                                    {
                                        string description = elementEncoded.Value;

                                        int posEndArrow = description.IndexOf("/>");

                                        if (posEndArrow != -1)
                                        {
                                            description = description.Insert(posEndArrow + 2, "<p/>");
                                        }

                                        string thumbnail = string.Empty;

                                        int posThumbnail = description.IndexOf("<!-- thumbsrc: ");
                                        int posEndThumbnail = description.IndexOf(" -->");

                                        if (posEndArrow != -1 && posEndArrow != -1)
                                        {
                                            thumbnail = description.Substring(posThumbnail + 15, posEndThumbnail - posThumbnail - 15);
                                        }

                                        description = Regex.Replace(description, "<img(.+?)/>", "<p><img $1></p>");

                                        getArticlesRequestArgs.Articles.Add(new Article(guid,
                                                                                        GetElementValue(itemElement, "title"),
                                                                                        description, publishDate,
                                                                                        GetElementValue(itemElement, "{http://purl.org/dc/elements/1.1/}creator"),
                                                                                        thumbnail));
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                        getArticlesRequestArgs.IsSuccess = false;
                    }
                }

                InvokeCallback(getArticlesRequestArgs);
            }
        }

        #endregion
    }
}